package phonecompany.phone;

import java.io.Serializable;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.LinkedList;

import phonecompany.PhoneManager;
import phonecompany.PhoneManagerService;
import phonecompany.account.Account;
import phonecompany.account.PhoneAccount;
import phonecompany.call.Call;

/**
 * @since Oct 24, 2011
 * @author <a href="mailto:zexpp5@gmail.com">Zexu.Lin</a>
 * @version $Id: Phone.java 29 2011-10-30 21:54:06Z zexpp5@gmail.com $
 * 
 */
public class Phone implements Serializable{
	private PhoneAccount phoneAccount;
	private LinkedList<Call> callsList;

	private Phone() {
	}

	public Phone(PhoneAccount phoneAccount) {
		this.phoneAccount = phoneAccount;
		this.callsList = new LinkedList<Call>();
	}

	public PhoneNumber getPhoneNumber() {
		return phoneAccount.getNumber();
	}

	public double getBalance() {
		return phoneAccount.getBalance();
	}

	public boolean call(PhoneNumber toNumber, int duration) {
		Call c = null;
		try {
			c = new Call(phoneAccount.getNumber(), toNumber, duration);
			phoneAccount.chargeCall(toNumber, duration);
			return true;
		} catch (Exception e) {

			e.printStackTrace();
			return false;
		} finally {
			callsList.add(c);
		}

	}

	public LinkedList<Call> getRecentCalls() {
		return callsList;
	}

	public void clearCallsList() {
		this.callsList = new LinkedList<Call>();
	}

	public boolean credit(int pounds) {
		if (!phoneAccount.isBlocked()) {
			phoneAccount.creditAccount(pounds);
			return true;
		}
		return false;

	}
	
	
	public Account getAccountFromServer(PhoneNumber pn){
		PhoneManagerService service = null;
		try {
			service = (PhoneManagerService) Naming.lookup("PhoneManagerService");
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NotBoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Account acc = service.echoPhoneAccount(this.getPhoneNumber().toString());
		
		return acc;
	}

	@Override
	public String toString() {
		return this.getPhoneNumber().toString();
	}

	@Override
	public boolean equals(Object obj) {
		if (this.hashCode() == obj.hashCode())
			return true;

		return false;
	}

	@Override
	public int hashCode() {
		int hc = 17;
		hc = 37 * hc
				+ (this.toString() == null ? 0 : this.toString().hashCode());
		return hc;
	}
}
